<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useDidShow, usePullDownRefresh, useReachBottom, useReady, useRouter } from '@tarojs/taro';
import { Edit, Search2, Uploader } from '@nutui/icons-vue-taro';
import { cloneDeep } from 'lodash-es';
import type { Book, Receiving } from '@/interface';
import { pageReceiving } from '@/service/api';

const stickyHeight = ref<number>(0);
// tab页下面的商品列表
const receivingList = ref<Array<Receiving>>([]);

const book = ref<Book>({ id: '', userId: '', bookName: '', receiveDate: '', coverId: '' });

/**
 * 初始化分页请求参数
 */
const initPageParam = () => {
  return {
    current: 1,
    size: 10,
    orderItems: new Array<Common.OrderItem>({
      column: 'createAt',
      asc: false
    })
  } as Common.Page<Receiving>;
};

const pageParam = ref<Common.Page<Receiving>>(initPageParam());
const flushed = ref<boolean>(true);

const requestPage = (data: Common.Page<Receiving>) => {
  pageReceiving(data).then((res: Service.SuccessResult) => {
    if (res.success && res.success.records && res.success.records.length) {
      receivingList.value = [...receivingList.value, ...res.success.records];
    } else {
      flushed.value = false;
    }
  });
};

/**
 * 跳转到回礼记录页面
 * @param row 当前收礼记录
 */
const onReciprocation = (row: Receiving) => {
  const row1: Receiving = cloneDeep(row);
  row1.receiveDate = book.value.receiveDate;
  Taro.navigateTo({
    url: `/package/reciprocation/index?bookId=${row.bookId}&receivingId=${row.id}`,
    success(res) {
      res.eventChannel.emit('initData', row1);
    }
  });
};

const flushData = () => {
  flushed.value = true;
  pageParam.value = initPageParam();
  const eq = {
    column: 'bookId',
    operator: 'EQ',
    and: true,
    value: book.value.id
  } as Common.MatchItem;
  pageParam.value.matchItems = [...new Array(eq)];
  receivingList.value = [];
  requestPage(pageParam.value);
};

/**
 * 点击设置，跳转到修改页面
 * @param row
 */
const onSetting = (row: Receiving) => {
  Taro.navigateTo({
    url: `/package/receiving-adder/index?tag=setting`,
    events: {
      flushData() {
        flushData();
      }
    },
    success(res) {
      res.eventChannel.emit('initData', row);
    }
  });
};

/**
 * 点击新增收礼记录
 */
const onReceiving = () => {
  Taro.navigateTo({
    url: `/package/receiving-adder/index?bookId=${book.value.id}&receiveDate=${book.value.receiveDate}`,
    events: {
      flushData() {
        flushData();
      }
    }
  });
};

useReady(() => {
  Taro.nextTick(() => {
    Taro.createSelectorQuery()
      .select('#receiving-search')
      .boundingClientRect()
      .exec(res => {
        const { bottom } = res[0];
        stickyHeight.value = bottom;
      });
  });
});

usePullDownRefresh(() => {
  Taro.showLoading({
    title: '加载中...',
    mask: true
  });
  flushData();
  Taro.stopPullDownRefresh();
  Taro.hideLoading();
});

useReachBottom(() => {
  if (flushed.value) {
    Taro.showLoading({
      title: '加载中...',
      mask: true
    });
    pageParam.value.current += 1;
    requestPage(pageParam.value);
    Taro.hideLoading();
  }
});

onMounted(() => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().on('initData', (data: Book) => {
    book.value.id = data.id!;
    book.value.bookName = data.bookName!;
    book.value.receiveDate = data.receiveDate!;
    book.value.coverId = data.coverId;
    book.value.remark = data.remark;
    book.value.receiveAmount = data.receiveAmount;
  });
  const { params } = useRouter();
  pageParam.value = initPageParam();
  const eq = {
    column: 'bookId',
    operator: 'EQ',
    and: true,
    value: params.bookId
  } as Common.MatchItem;
  pageParam.value.matchItems = [...new Array(eq)];
  requestPage(pageParam.value);
});

/**
 * 点击首页搜索框，跳转到商品列表页，并自动聚焦输入框
 */
const onSearch = () => {
  Taro.navigateTo({
    url: '/package/search/index',
    events: {
      searchConfirm(data: { searchValue: string }) {
        const eq = {
          column: 'bookId',
          operator: 'EQ',
          and: true,
          value: book.value.id
        } as Common.MatchItem;
        const like = {
          column: 'guestName',
          operator: 'LIKE',
          and: true,
          value: data.searchValue
        } as Common.MatchItem;
        pageParam.value.matchItems = [...new Array(eq), ...new Array(like)];
        pageParam.value.current = 1;
        receivingList.value = [];
        requestPage(pageParam.value);
      }
    }
  });
};
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar left-show title="收礼记录" />
    <div class="w-375px text-30px">
      <!--搜索-->
      <nut-searchbar
        id="receiving-search"
        :background="'#fff'"
        :input-background="'#fafafa'"
        placeholder="请输入宾客姓名"
        readonly
        disabled
        class="search-input"
        @click-input="onSearch"
      >
        <template #leftin>
          <Search2 />
        </template>
      </nut-searchbar>
      <!--人亲列表-->
      <nut-cell-group class="pt-50px pl-16px pr-16px">
        <nut-cell center>
          <template #title>
            <div class="color-#666 font-bold text-16px">
              {{ book.bookName }}
            </div>
            <div class="color-#666 text-12px pt-8px">
              {{ book.receiveDate }}
            </div>
            <div class="color-#666 text-12px">
              {{ book.remark }}
            </div>
          </template>
          <template #desc>
            <div>
              <div class="color-#666 font-bold flex-center pb-10px text-18px">总收礼</div>
              <nut-price
                class="receiving-total"
                :price="book.receiveAmount"
                :decimal-digits="0"
                thousands
                :need-symbol="true"
                symbol="元"
                position="after"
              />
            </div>
          </template>
        </nut-cell>
      </nut-cell-group>
      <nut-sticky :top="stickyHeight">
        <nut-button block class="hoo-btn hoo-btn--dashed" @click="onReceiving">
          <template #icon>
            <Uploader color="#9ca3af" size="12px" />
          </template>
          <template #default>
            <span class="color-#9ca3af text-12px">点击新增收礼记录</span>
          </template>
        </nut-button>
      </nut-sticky>
      <scroll-view>
        <nut-cell-group class="receiving-list">
          <nut-cell
            v-for="(item, index) in receivingList"
            :key="index"
            center
            size="large"
            @click="onReciprocation(item)"
          >
            <template #icon>
              <!--<nut-avatar color="white" bg-color="#F44336">礼</nut-avatar>-->
              <nut-avatar color="#666">礼</nut-avatar>
            </template>
            <template #title>
              <div class="pl-10px flex-justify-center w-200px">
                <span class="receiving-name">{{ item.guestName }}</span>
                <nut-tag v-if="item.reciprocated" class="receiving-tag" color="#22c3aa">已回礼</nut-tag>
                <nut-tag v-else class="receiving-tag" color="#e9e9e9" text-color="#999999">未回礼</nut-tag>
              </div>
              <span class="receiving-desc">{{ item.remark || '--' }}</span>
            </template>
            <template #desc>
              <div class="h-28px flex-center float-right text-20px color-#666 font-bold mr-8px">
                {{ item.amount }}
              </div>
            </template>
            <template #link>
              <div class="w-50px h-50px relative flex-center" @click.stop="onSetting(item)">
                <Edit color="#666666" size="16px" />
              </div>
            </template>
          </nut-cell>
        </nut-cell-group>
      </scroll-view>
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';

.search-input {
  display: flex;
  position: fixed;
  z-index: 99;
  box-shadow: none;
  margin-top: -1px;
}

.receiving-total {
  color: #666;
  display: flex;
  justify-content: center;
  align-items: baseline;

  .nut-price--normal {
    font-size: 18px;
    font-weight: bold;
  }

  .nut-price--symbol {
    font-size: 10px;
  }
}

.receiving-list {
  padding: 0 16px;

  .receiving-name {
    display: inline-block;
    //width: 60px;
    font-weight: bold;
    color: #666666;
  }

  .receiving-tag {
    font-size: 10px;
    margin-left: 5px;
    height: 12px;
  }

  .receiving-desc {
    font-size: 12px;
    padding: 10px 0 0 10px;
  }
}
</style>
